package com.kedacom.demo;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class Upload {

	public static final String UTF8 = "UTF-8";

	public String doPost(String url, String moid, String folder, String... filenames)
			throws ClientProtocolException, IOException {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		MultipartEntityBuilder builder = MultipartEntityBuilder.create();
		builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

		builder.addPart("moid", new StringBody(moid, ContentType.TEXT_PLAIN));
		int index = 0;
		for (String filename : filenames) {
			builder.addPart("file" + ++index, new FileBody(new File(folder, filename)));
		}

		HttpEntity entity = builder.build();
		httpPost.setEntity(entity);
		HttpResponse response = httpClient.execute(httpPost);
		return readResponse(response, "utf-8");
	}

	public static void main(String[] args) throws ClientProtocolException, IOException {
		Upload upload = new Upload();
		System.out.println(upload.doPost("http://127.0.0.1:8080/upload/upload", "6ec778b8bd1448d3a03d91442f6c2c7c",
				"C:\\Users\\Administrator\\Desktop\\files\\h\\6ec778b8bd1448d3a03d91442f6c2c7c", "h40.jpg", "h64.jpg",
				"h128.jpg", "h256.jpg"));
	}

	/**
	 * 读取相应值，非200状态返回null
	 */
	private static String readResponse(HttpResponse response, String encoding) throws IOException {
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			StringBuffer result = new StringBuffer();
			HttpEntity httpEntity = response.getEntity();
			InputStream inputStream = httpEntity.getContent();
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, encoding));
			String readLine = null;
			while ((readLine = bufferedReader.readLine()) != null) {
				result.append(readLine);
			}
			inputStream.close();
			bufferedReader.close();
			return result.toString();
		} else {
			System.err.println("非200，状态值=" + response.getStatusLine().getStatusCode());
			return null;
		}
	}

}
